package com.example.socket.server.aio;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    //线程池
    private ExecutorService executorService;
    //线程组
    private AsynchronousChannelGroup channelGroup;
    //服务器通道
    public AsynchronousServerSocketChannel serverSocketChannel;

    public Server(int port){
        try {
            //创建一个线程池
            executorService = Executors.newCachedThreadPool();
            //创建一个线程组
            channelGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService,1);
            //创建服务器通道
            serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup);
            //进行端口绑定
            serverSocketChannel.bind(new InetSocketAddress(port));
            //进行阻塞（内部递归调用）
            serverSocketChannel.accept(this,new ServerCompletionHandler());
            //一直阻塞，不让服务停止
            Thread.sleep(Integer.MAX_VALUE);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Server(9000);
    }
}
